package leetcode.string;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Lc1419 {

    public int minNumberOfFrogs(String croakOfFrogs) {
        List<StringBuilder> list = new ArrayList<>();
        HashMap<Character, Character> preChar = new HashMap<>(); //保存每个字符的前一个字符
        preChar.put('r', 'c');
        preChar.put('o', 'r');
        preChar.put('a', 'o');
        preChar.put('k', 'a');
        HashMap<Character, Integer> cnt = new HashMap<>(); //保存每个字符在出现的次数
        char[] chars = {'c', 'r', 'o', 'a', 'k'};
        int ans = -1;
        for (int i = 0; i < croakOfFrogs.length(); i++) {
            char c = croakOfFrogs.charAt(i);
            int count = cnt.getOrDefault(c, 0);
            cnt.put(c, ++count);
            if (c != 'c' && (!cnt.containsKey(preChar.get(c)) || count > cnt.get(preChar.get(c)))) {
                return -1;
            }
            if (count > list.size()) {//c 字符
                list.add(new StringBuilder(c + ""));
            } else {
                list.get(count - 1).append(c);
            }
            if (c == 'k') {
                ans = Math.max(ans, list.size());
                list.remove(0);
                for (int j = 0; j < chars.length; j++) {
                    cnt.put(chars[j], cnt.get(chars[j]) - 1);
                }
            }
        }
        if (list.size() != 0) return -1;
        return ans;
    }

    public static void main(String[] args) {
        Lc1419 lc1419 = new Lc1419();
        System.out.println(lc1419.minNumberOfFrogs("croakcroak"));
//        StringBuilder builder = new StringBuilder("s");
//        builder.append('2');
//        System.out.println(builder.toString());
    }


}
